<template>
  <div v-loading="devLoading" class="connect">
    <div class="connect_box">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item :label="$t('Order_module.User')">
          <el-input v-model="formInline.userName" :placeholder="$t('Order_module.User')"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" >{{$t('public.query')}}</el-button>
        </el-form-item>
      </el-form>
      <div class="btns_ayyay">
         <el-button @click="addModule">{{$t('Order_module.newly_added')}}</el-button>
      </div>
      <div class="table_">
        <el-table :cell-style="cell_style" :data="tableData" border  style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column align="center" type="selection" width="55"> </el-table-column>
          <el-table-column align="center" prop="userName" :label="$t('Order_module.corporate_name')"  min-width="180"> </el-table-column>
          <el-table-column  align="center" prop="Batch_number" :label="$t('Order_module.Template_ID')"  min-width="180">
              <template   slot-scope="scope">
                <div class="box_item_box">
                  <div v-for="(item,index) in scope.row.list" class="box_item">{{item.id}}</div>
                </div>

              </template>
          </el-table-column>
          <el-table-column align="center" prop="Batch_number" :label="$t('Order_module.area')"  min-width="380">
            <template slot-scope="scope">
              <div class="box_item_box">
                <div v-for="(item,index) in scope.row.list" class="box_item over">
                    {{item.areaName}}

                </div>
              </div>

            </template>
          </el-table-column>
          <el-table-column align="center" prop="Batch_number" :label="$t('Order_module.Billing_gear')+'(KG)'"  min-width="180">
            <template   slot-scope="scope">
              <div class="box_item_box">
                <div v-for="(item,index) in scope.row.list" class="box_item">
                  {{item.firstWeight}}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="Batch_number" :label="$t('Order_module.First_weight_calculation')"  min-width="180">
            <template   slot-scope="scope">
              <div class="box_item_box">
                <div v-for="(item,index) in scope.row.list" class="box_item">
                  {{item.initialAmount}}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="Batch_number" :label="$t('Order_module.Continuation_gear')+'(KG)'"  min-width="180">
            <template   slot-scope="scope">
              <div class="box_item_box">
                <div v-for="(item,index) in scope.row.list" class="box_item">
                  {{item.addWeight}}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="Batch_number" :label="$t('Order_module.Renewal_billing')"  min-width="180">
            <template   slot-scope="scope">
              <div class="box_item_box">
                <div v-for="(item,index) in scope.row.list" class="box_item">
                  {{item.renewalAmount}}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="Batch_number" fixed="right" :label="$t('public.operate')" min-width="180">
            <template   slot-scope="scope">
              <el-button @click="disable(scope.row)" type="text">{{$t('public.modify')}}</el-button>
              <el-popconfirm
                @confirm="deletes(scope.row)"
                :confirm-button-text="$t('public.determine')"
                :cancel-button-text="$t('public.cancellation')"
                :title="$t('public.Are_you_sure_about_this_operation')"
              >
              <el-button  type="text" style="color: red;"  slot="reference" size="small">{{$t('public.delete') }}</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </div>

        <div style="margin-top: 20px;"></div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 50, 200, 400]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </div>
    <el-dialog :title="$t('Order_module.Billing_template')"  :visible.sync="disableShow" width="60%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
        <el-form-item v-if="addType==1" prop="template.userName"
         :rules="[
            { required: true, message:$t('public.Enter'), trigger: 'blur'},
          ]"
         :label="$t('Order_module.user_account')">
            <el-select style="width: 100%;" v-model="ruleForm.template.userName" filterable :placeholder="$t('Order_module.user_account')">
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.userName"
                :value="item.id">
              </el-option>
            </el-select>
        </el-form-item>
        <!-- 模版列表 -->
        <div v-if="moBanList.length>0">
          <div v-for="(item,index) in ruleForm.template.list" :key="index">
            <el-form-item  :label="$t('Order_module.Region_Selection')" prop="name">
              <el-checkbox-group v-model="checkedCities">
                <el-checkbox
                @change="choosecheckbox(item.gearPosition , ind , item)"
                v-for="(ite,ind) in shengL" :label="ite.areaName" :key="ind"
                :disabled="ite.gearPosition!=item.gearPosition && ite.checked==true"
                >{{ite.areaName}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
            :prop="'template.list.'+index+'.firstWeight'"
             :rules="[
               { required: true, message:$t('public.Enter'), trigger: 'blur'},
             ]"
             :label="$t('Order_module.First_weight_gear')">
                <el-input
                  @input="number($event , index , 'firstWeight')" type="text" maxlength="5" show-word-limit
                 style="width: 100%;"  v-model="item.firstWeight" :placeholder="$t('Order_module.First_weight_gear')"></el-input>
            </el-form-item>
            <el-form-item
            :prop="'template.list.'+index+'.initialAmount'"
            :rules="[
               { required: true, message:$t('public.Enter'), trigger: 'blur'},
             ]"
            :label="$t('Order_module.Initial_amount')">
                <el-input style="width: 100%;"
                @input="number($event , index , 'initialAmount')" type="text" maxlength="10" show-word-limit
                 v-model="item.initialAmount" :placeholder="$t('Order_module.Initial_amount')"></el-input>
            </el-form-item>
            <el-form-item
            :prop="'template.list.'+index+'.addWeight'"
            :rules="[
               { required: true, message:$t('public.Enter'), trigger: 'blur'},
             ]"
            :label="$t('Order_module.Continuous_weight_gear')">
                <el-input
                 @input="number($event , index , 'addWeight')" type="text" maxlength="5" show-word-limit
                 style="width: 100%;" v-model="item.addWeight" :placeholder="$t('Order_module.Continuous_weight_gear')"></el-input>
            </el-form-item>
            <el-form-item
            :prop="'template.list.'+index+'.renewalAmount'"
            :rules="[
               { required: true, message:$t('public.Enter'), trigger: 'blur'},
             ]"
            :label="$t('Order_module.Renewal_amount')">
                <el-input
                 @input="number($event , index , 'renewalAmount')" type="text" maxlength="10" show-word-limit
                 style="width: 100%;"  v-model="item.renewalAmount" :placeholder="$t('Order_module.Renewal_amount')"></el-input>
            </el-form-item>
            <div style="padding: 15px 0%;display: flex;justify-content: flex-end;">
              <el-button type="danger" @click="dle(index , item)">{{$t('Order_module.Delete_Template')}}</el-button>
            </div>

          </div>
        </div>


        <el-form-item>
          <el-button type="primary" @click="add()">{{$t('Order_module.Add_Template')}}</el-button>

        </el-form-item>
      </el-form>
      <div style="display: flex;justify-content: flex-end;">
          <el-button @click="disableShow=false">{{$t('public.cancellation')}}</el-button>
          <el-button :loading="submitFormLoading" @click="submitForm('ruleForm')" type="primary">{{$t('public.determine')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
  import {
    template_list,
    template_info,
    template_save,
    template_update,
    area_select,
    user_list,
    getTemplateUser,
    template_delete
  } from '@/api/wqzApi'
  export default {
    components: {},
    data() {
      var ruleChange = (rule, value, callback) => {
        console.log(value , '888888')
            return
              if (value === '') {
                callback(new Error('请再次输入密码'));
              } else if (value !== this.ruleForm.pass) {
                callback(new Error('两次输入密码不一致!'));
              } else {
                callback();
              }
            }
      return {
        devLoading:false,
        submitFormLoading:false,
        addType:null,//编辑类型 1添加 0修改
        input:'',
        ClickItem:{},
        cell_style: {
          'flex-direction': 'column',
          'height': 'auto',
          'position': 'relative',
          'height': '100%',
          'padding': 0
        },
        userList:[

        ],//用户账户列表
        moBanList:[ //模版列表

        ],
        rules:{
          userName:[
               { required: true, message: '请选择', trigger: 'change' }
          ],

        },
        ruleForm:{
          // 计费模版
        },
        disableShow:false, //计费模版对话框
        checkedCities:[],
        shengL:[], //省份列表
        value:null,
        cell_style:{
          'flex-direction': 'column',
          'height':'auto',
          'position':'relative',
          'height':'100%',
          'padding':0,
        },
        options:[],
        total:100,
        limit:10,
        page:1,
        tableData:[],
        formInline:{
          userName:'',
        }
      }
    },

    created() {

    },
    mounted() {
      var params = this.$getUrlParams()
      if(params.name){
        this.formInline.userName = decodeURIComponent(params.name)
      }
      this.getList()
      this.getUserList()
    },
    destroyed() {

    },
    methods: {
      search(){
        this.page = 1
          this.getList()
      },
      // 删除用户
      deletes(item){
        var arr = []
        item.list.forEach((ite,index)=>{
          arr.push(ite.id)
        })
        template_delete(arr).then(res=>{
          this.$message({
            type:'success',
            message: this.$t('public.Operation_successful'),
          })
          this.getList()
        })
      },
      getUserList(){
        // 获取用户账号列表
        getTemplateUser().then(res=>{
          this.userList = res.userList
        })
      },
      number(e,index,value){
        // this.ruleForm.template.list[index][value] = e.replace(/[^0-9 .]/g,'')
        this.ruleForm.template.list[index][value] = this.$geShi(e)
      },
      submitForm(ref){
        // 模版修改

         this.$refs[ref].validate((valid) => {
           this.submitFormLoading = true
          if (valid) {
            this.ruleForm.template.list.forEach((item,index)=>{
              var arr = []
              this.ruleForm.template.list[index].addWeight = Number(item.addWeight)
              this.ruleForm.template.list[index].firstWeight = Number(item.firstWeight)
              this.ruleForm.template.list[index].initialAmount = Number(item.initialAmount)
              this.ruleForm.template.list[index].renewalAmount = Number(item.renewalAmount)
              this.ruleForm.template.areaList.forEach((ite,ind)=>{
                if(item.gearPosition == ite.gearPosition){
                  arr.push(ite.id)
                }
              })
              this.ruleForm.template.list[index].areaName = arr.join(',')
            })
            var data = this.ruleForm.template.list
            var tost = false
            this.shengL.forEach((value , key)=>{
                if(value.checked==false){
                  tost = true
                }
            })
            if(tost){
              this.$message({
                type:'error',
                message:this.$t('Order_module.Please_select_all_regions')
              })
              this.submitFormLoading = false
              return
            }
            if(this.addType == 0){
              // 编辑已有模版
              data.forEach((item,index)=>{
                data[index].userId = this.ClickItem.list[0].userId
              })
              template_update(data).then(res=>{
                this.$message({
                  type:'success',
                  message:this.$t('public.Operation_successful')
                })
                this.disableShow = false
                this.submitFormLoading = false
                this.getList()
              }).catch((err)=>{
              this.submitFormLoading = false
              })
            }else{
              // 添加新模版
              data.forEach((item,index)=>{
                data[index].userId = this.ruleForm.template.userName
              })
              template_save(data).then(res=>{
                this.$message({
                  type:'success',
                  message:this.$t('public.Operation_successful')
                })
                this.disableShow = false
                this.submitFormLoading = false
                this.getList()
              }).catch((err)=>{
               this.submitFormLoading = false
              })
            }

          } else {
            this.submitFormLoading = false
            return false;
          }
        });
      },
      getList(){
        // 获取列表
        var arr = []
        var data = {
          limit:this.limit,
          page:this.page,
          ...this.formInline
        }
        template_list(data).then(res=>{
          this.tableData = res.page.list
          var arr = []
          this.shengL.forEach((item,index)=>{
            if(item.checked == true){
              arr.push(item.areaName)
            }
          })
          this.checkedCities = arr
          this.total = res.page.totalCount
          console.log(res)
        })

      },
      choosecheckbox(index , ind , item){
        // 模版选择省份
        this.shengL[ind].gearPosition = index
        this.shengL[ind].checked = !this.shengL[ind].checked
        var arr = []

        this.shengL.forEach((item,index)=>{
          if(item.checked == true){
            arr.push(item.areaName)
          }
        })
        this.checkedCities = arr
      },
       handleCheckedCitiesChange(value) {
        console.log(value)
      },
      add(){
        var length = this.ruleForm.template.list.length+1
        this.ruleForm.template.list.push({
            areaName : '',
            addWeight : null,
            firstWeight : null,
            initialAmount : null,
            renewalAmount : null,
            gearPosition :length,
            userId:null,
        })
      },
      dle(index , item){

        this.shengL.forEach((ite,ind)=>{
          if(item.gearPosition == ite.gearPosition){
            this.shengL[ind].gearPosition = ''
            this.shengL[ind].checked = false
          }
        })
        this.gengXin()
        this.moBanList.splice(index,1)

      },
      gengXin(){
        var arr = []
        this.shengL.forEach((item,index)=>{
          if(item.checked == true){
            arr.push(item.areaName)
          }
        })
        this.checkedCities = arr
      },
      disable(item){
        // 获取模版详情
        this.ClickItem = item
        var data = {
          userId:item.list[0].userId
        }
        this.devLoading = true
        this.addType = 0
        template_info(data).then(res=>{
          this.moBanList = res.template.list //模版lisr赋值
          this.shengL = res.template.areaList //所有省份赋值
          this.shengL.forEach((item,index)=>{
            this.shengL[index].checked = true //所有的省份都选中
          })
          this.ruleForm = res
          console.log( this.ruleForm)
          this.gengXin()
          this.disableShow=!this.disableShow
          this.devLoading = false
        }).catch(err=>{
          this.devLoading = false
        })
      },
      addModule(){
        // 点击添加新模版对话框
        area_select().then(res=>{
          this.addType=1
          var arr = []
          for(var i=0 ; i<res.total ; i++){
            arr.push({
              areaName : '',
              addWeight : null,
              firstWeight : null,
              initialAmount : null,
              renewalAmount : null,
              gearPosition :i+1,
              userId:null
            })
          }
          res.list.forEach((item,index)=>{
            res.list[index].checked = true
          })
          this.ruleForm = {
            template:{
              areaList:res.list,
              list:arr,
              userName:null
            }
          }
          this.shengL = []
          this.shengL = res.list
          this.gengXin()
          this.moBanList = arr
          this.disableShow=!this.disableShow
        })
      },
      handleSelectionChange(e){
        console.log(e)
      },
      handleSizeChange(e){
        console.log(e)
        this.limit = e
        this.getList()

      },
      handleCurrentChange(e){
        this.page = e
        this.getList()

      }
    }
  }
</script>

<style scoped>
  @import url('Billing_management.css');
</style>
